#!/usr/bin/env bash

# 简单接口冒烟测试脚本（无需额外依赖）
# 用法：
#   bash scripts/smoke_test.sh               # 使用默认 http://127.0.0.1:8206
#   BASE_URL=http://cdsgjs.com:8206 bash scripts/smoke_test.sh

BASE_URL=${BASE_URL:-http://127.0.0.1:8206}

sep() {
	echo "------------------------------------------------------------"
}

call() {
	local method="$1"
	local path="$2"
	local data="$3" # 可为空
	local url="${BASE_URL}${path}"

	if [ -n "$data" ]; then
		resp=$(curl -sS -H 'Content-Type: application/json' -X "$method" "$url" -d "$data" -w ' HTTP_STATUS:%{http_code}')
	else
		resp=$(curl -sS -X "$method" "$url" -w ' HTTP_STATUS:%{http_code}')
	fi

	body=${resp% HTTP_STATUS:*}
	status=${resp##*HTTP_STATUS:}
	echo "$body"
	echo "$status"
}

assert_contains() {
	local body="$1"
	local needle="$2"
	if echo "$body" | grep -q "$needle"; then
		return 0
	else
		return 1
	fi
}

test_case() {
	local name="$1"
	local method="$2"
	local path="$3"
	local data="$4"
	local expect_substr="$5" # 期望响应体包含的片段，可留空

	sep
	echo "[TEST] $name -> $method $path"
	read -r body status < <(call "$method" "$path" "$data")

	local ok=1
	if [ "$status" != "200" ]; then
		ok=0
	fi
	if [ -n "$expect_substr" ]; then
		if ! assert_contains "$body" "$expect_substr"; then
			ok=0
		fi
	fi

	if [ $ok -eq 1 ]; then
		echo "[PASS] $name"
	else
		echo "[FAIL] $name"
	fi
	# 打印简要摘要（最多 300 字符）
	echo "RESPONSE: $(echo "$body" | head -c 300)"
	echo "STATUS: $status"
}

echo "Base URL: ${BASE_URL}"

# 1. 健康检查
test_case "health" GET "/" "" '"status":"ok"'

# 2. 区服列表
test_case "area list" GET "/user-service/area/list" "" '"code":0'

# 3. 获取短信验证码（模拟）
test_case "captcha" POST "/user-service/user/captcha" '{"mobile":"13800000000","captcha":"123456"}' '"code":0'

# 4. 微信支付下单（模拟）
test_case "weixin pay" POST "/user-service/recharage/weixin" '{"totalFee":1}' '"code":0'

# 5. 微信网页授权（模拟）
test_case "weixin auth" GET "/user-service/user/weixinAuth?code=abcdef" "" '"code":0'

# 6. 图形验证码（图片），仅校验 200 状态
test_case "captcha image" GET "/user-service/user/captchaImg?moblie=13800000000" "" ""

sep
echo "Done."

